﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Clipboard.Tools
{
    public class IpHelper
    {
        private static readonly HttpClient client = new HttpClient();
        private static readonly string apiToken = "48f26f4522f0434c8a6e84cd9b30c575";

        //public static string GetLocalIP()
        //{
        //    string localIP = string.Empty;
        //    try
        //    {
        //        var host = Dns.GetHostEntry(Dns.GetHostName());
        //        foreach (var ip in host.AddressList)
        //        {
        //            if (ip.AddressFamily == AddressFamily.InterNetwork) // IPv4
        //            {
        //                localIP = ip.ToString();
        //                break;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine("Error: " + ex.Message);
        //    }
        //    return localIP;
        //}

        public string GetLocalIP()
        {
            string localIP = string.Empty;
            using (var socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, 0))
            {
                socket.Connect("8.8.8.8", 65530);
                var endPoint = socket.LocalEndPoint as System.Net.IPEndPoint;
                localIP = endPoint.Address.ToString();
            }
            return localIP;
        }
        public async Task<string> GetGeolocation(string ip)
        {
            if (string.IsNullOrWhiteSpace(ip))
            {
                return string.Empty;
            }
            try
            {
                string apiUrl = $"https://eolink.o.apispace.com/ipv4street/ip/geo/v1/street/biz?ip={ip}&area=single";
                client.DefaultRequestHeaders.Add("X-APISpace-Token", apiToken);

                HttpResponseMessage response = await client.GetAsync(apiUrl);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                JObject json = JObject.Parse(responseBody);

                if (json["code"].ToString() == "Success")
                {
                    return json["data"]["multiAreas"][0]["address"].ToString() + "-" + json["data"]["owner"];
                }
                else
                {
                    return "未知";
                }
            }
            catch
            {
                return string.Empty;
            }
        }
    }

    public class IpInfoDto
    {
        /// <summary>
        /// ip
        /// </summary>
        [JsonProperty("ip")]
        public string Ip { get; set; }

        /// <summary>
        /// 省份
        /// </summary>
        [JsonProperty("pro")]
        public string Province { get; set; }

        /// <summary>
        /// 省编码
        /// </summary>
        [JsonProperty("proCode")]
        public string ProCode { get; set; }

        /// <summary>
        /// 城市
        /// </summary>
        [JsonProperty("city")]
        public string City { get; set; }

        /// <summary>
        /// 城市编码
        /// </summary>
        [JsonProperty("cityCode")]
        public string CityCode { get; set; }

        /// <summary>
        /// 区域
        /// </summary>
        [JsonProperty("region")]
        public string Region { get; set; }

        /// <summary>
        /// 区编码
        /// </summary>
        [JsonProperty("regionCode")]
        public string RegionCode { get; set; }

        /// <summary>
        /// IP归属地
        /// </summary>
        [JsonProperty("addr")]
        public string Address { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [JsonProperty("regionNames")]
        public string RegionNames { get; set; }

        /// <summary>
        /// 错误信息
        /// </summary>
        [JsonProperty("err")]
        public string Error { get; set; }
    }
}
